<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-5-3
 * Time: 下午5:04
 */
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
loadcache('plugin');
$set= $_G['cache']['plugin']['iExam'];
require_once "function.php";
include template('iexam:header_json');
if($_POST['formhash'] == formhash()){
	$message = '<h2>考试题目：'.$_POST['title'].'</h2><ul>';
	foreach($_POST['answer'] AS $k => $v){
		$question[] = array(
			'answer' => $v,
			'istrue' => ($k == $_POST['istrue'])?1:0
		);
		if($k == $_POST['istrue'])
			$message .= '<li style="color:Red"><h4><strong>'.chr(65+$k).'：'.$v.'</strong>（正确答案）</h4></li>';
		else
			$message .= '<li><h4><strong>'.chr(65+$k).'：'.$v.'</strong></h4></li>';
	}
	$message .= '</ul><h2>试题解析</h2><p>'.$_POST['description'].'</p>';
	$theads = array(
		'fid'       => $set['examForum'],
		'author'    => $_G['username'],
		'authorid'  => $_G['uid'],
		'subject'   => $_POST['title'],
		'dateline'  => time(),
		'lastpost'  => time(),
		'lastposter'=> $_G['username'],
		'views'     => 1
	);
	$post = array(
		'title'     => $_POST['title'],
		'catid'     => $_POST['catid'],
		'type'      => $_POST['type'],
		'isneed'    => $_POST['isneed'],
		'score'     => $_POST['score'],
		'question' => serialize($question),
		'displayorder'=> $_POST['displayorder'],
		'description'=> $_POST['description']
	);
	if($_POST['apply_action'] == 'Add'){
		$post['tid'] = DB::insert('forum_thread', $theads, 1);
		$theads = array_merge($theads, array('tid' => $post['tid'], 'first' => 1, 'message' => $message, 'htmlon' => 1));
		unset($theads['lastpost'], $theads['lastposter'], $theads['views']);
		require './source/function/function_forum.php';
		$post['pid'] = insertpost($theads);
		DB::insert('plugin_iexam', $post, 1);
		$message = "新增考试试题提交成功！";
	}
	if($_POST['apply_action'] == 'Edit'){
		DB::update('plugin_iexam', $post, "eid=".$_POST['eid']);
		DB::update('forum_thread', $theads, 'tid='.$_POST['tid']);
		$theads = array_merge($theads, array('tid' => $_POST['tid'], 'first' => 1, 'message' => $message, 'htmlon' => 1));
		unset($theads['lastpost'], $theads['lastposter'], $theads['views']);
		DB::update('forum_post', $theads, 'pid='.$_POST['pid']);
		$message = "修改编辑考试试题提交成功！";
	}
	if($_POST['apply_action'] == 'Del'){
		DB::delete('plugin_iexam', "eid=".$_POST['eid']);
		DB::delete('forum_thread', "tid=".$_POST['tid']);
		DB::delete('forum_post', "pid=".$_POST['pid']);
		$message = "删除考试试题提交成功！";
	}
	$exam = array('type' => 'success', 'msg' => $message);
}elseif(!is_null($_POST['eid'])){
	$exam = DB::fetch_first("SELECT * FROM ".DB::table('plugin_iexam')." WHERE eid = ".$_POST['eid']);
	$exam['question'] = unserialize($exam['question']);
}else{
	$exam = array();
}
echo json_encode($exam);